package com.cyjt.operation.ui;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cyjt.operation.R;
import com.cyjt.operation.base.AppContext;
import com.cyjt.operation.base.BaseActivityWithNFC;
import com.cyjt.operation.base.HandlerMessageCodes;
import com.cyjt.operation.bean.BaseStationInfo;
import com.cyjt.operation.bean.ParkingLot;
import com.cyjt.operation.fragment.DialogFragmentForBaseStationHeartBeats;
import com.cyjt.operation.fragment.DialogFragmentForSensorHeartBeats;
import com.cyjt.operation.fragment.DynamicPickBasestationDialogFragment;
import com.cyjt.operation.fragment.ParkingLotCheckFragment;
import com.cyjt.operation.fragment.ParkingLotCheckFragment.ParkingLotCheckFragListener;
import com.cyjt.operation.fragment.ParkingLotNewEditFragment;
import com.cyjt.operation.fragment.ParkingLotNewEditFragment.ParkingLotNewEditFragListener;
import com.cyjt.operation.sqlit.DBManager;
import com.cyjt.operation.uitools.CHexConver;
import com.cyjt.operation.uitools.CharacterTool2;
import com.cyjt.operation.uitools.HardwareInterfaceTools;

/**
 * 部署的Activity 车位信息界面<BR>
 * 包含节点以及地磁信息
 * 
 * @author kullo<BR>
 *         2014-10-28 上午9:10:20<BR>
 */
public class NewParkingLotInfoActivity extends BaseActivityWithNFC
		implements ParkingLotCheckFragListener, ParkingLotNewEditFragListener {
	private FragmentManager fragmentmanager;
	private ParkingLotCheckFragment plCheckFragment;
	// private ParkingLotEditFragment plEditFragment;
	private ParkingLotNewEditFragment plEditFragment;
	/** 当前页面标志，0表示查看页面、1标志编辑页面 */
	private int currentActionFlag = 1;
	private TextView actionbar_textView_title;
	private TextView actionbar_refresh_button;
	private Button jiedian_heart, jizhan_heart;
	private ParkingLot currentParkingLot;
	private BaseStationInfo currentBaseStation;
	private BaseStationInfo currentSupportBaseStation;
	private ProgressBar actionbar_progressBar;

	/** ==========蓝牙========== */
	private final static int REQUEST_CONNECT_DEVICE = 1; // 宏定义查询设备句柄

	private final static String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB"; // SPP服务UUID号

	private InputStream is; // 输入流，用来接收蓝牙数据
	// private TextView text0; //提示栏解句柄
	private String smsg = ""; // 显示用数据缓存
	private String fmsg = ""; // 保存用数据缓存

	public String filename = ""; // 用来保存存储的文件名
	BluetoothDevice _device = null; // 蓝牙设备
	BluetoothSocket _socket = null; // 蓝牙通信socket
	boolean isSocket = false; // 判断是否连接蓝牙成功
	boolean _discoveryFinished = false;
	boolean bRun = true;
	boolean bThread = false;
	public ConnectedThread mConnectedThread;

	@SuppressLint("NewApi")
	private BluetoothAdapter _bluetooth = BluetoothAdapter.getDefaultAdapter(); // 获取本地蓝牙适配器，即蓝牙设备
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case HandlerMessageCodes.HTTP_BUILDER_FETCH_PARKINGLOT_INFO_SUCCEED:
				if ((ParkingLot) msg.obj != null && !hasDismissed) {
					currentParkingLot = (ParkingLot) msg.obj;
					changeFragment(currentActionFlag);
					getBaseStationInfo();
				}
				break;
			case HandlerMessageCodes.HTTP_BUILDER_FETCH_PARKINGLOT_INFO_FAILED:

				break;
			case HandlerMessageCodes.HTTP_BUILDER_FETCH_BASESTATION_INFO_SUCCEED:
				currentBaseStation = (BaseStationInfo) msg.obj;
				break;
			case HandlerMessageCodes.HTTP_BUILDER_FETCH_BASESTATION_INFO_FAILED:

				break;
			case HandlerMessageCodes.HTTP_BUILDER_DELETE_NODE_INFO_SUCCEED:
				switch (msg.arg1) {
				case 0:
					currentParkingLot.setSensorCode("");

					break;
				case 1:
					currentParkingLot.setSensorCode1("");

					break;

				default:
					break;
				}
				// 删掉之后更新界面
				if (plEditFragment != null) {
					plEditFragment.refreshParkingLot(currentParkingLot);
				}
				break;
			case HandlerMessageCodes.HTTP_BUILDER_DELETE_NODE_INFO_FAILED:

				break;
			case HandlerMessageCodes.HTTP_BUILDER_DELETE_LOT_INFO_SUCCEED:
				// 删除车位成功
				onBackPressed();
				break;
			case HandlerMessageCodes.HTTP_BUILDER_DELETE_LOT_INFO_FAILED:

				break;
			case HandlerMessageCodes.SUBMIT_LOT_INFO_FAILED:

				break;
			case HandlerMessageCodes.SUBMIT_LOT_INFO_SUCCEED:
				Toast.makeText(NewParkingLotInfoActivity.this, "正在部署中,请稍后...", Toast.LENGTH_SHORT).show();
				// 编辑成功
				// onBackPressed();
				break;
			case HandlerMessageCodes.HTTP_BUILDER_SUBMIT_BASESTATION_MAPPING_SUCCEED:
				// 提交关系成功
				if (plEditFragment != null) {
					if (("").equals(currentParkingLot.getSensorCode())) {
						Log.i("demo", "nfcCode=" + nfcCode);
						currentParkingLot.setSensorCode(nfcCode);
					} else if (("").equals(currentParkingLot.getSensorCode1())) {
						currentParkingLot.setNfcCode(nfcCode);
					} else {
						// 没有多余的地方添加
						return;
					}
					plEditFragment.refreshParkingLot(currentParkingLot);
				}
				break;
			default:
				break;
			}
			stopProgress();
		}
	};
	private boolean isCurrentLotActivited = false;
	private boolean hasDismissed = false;

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		hasDismissed = true;
		if (_socket != null) // 关闭连接socket
			try {
				_socket.close();
			} catch (IOException e) {
			}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		fragmentmanager = getFragmentManager();
		daManager = new DBManager(NewParkingLotInfoActivity.this);
		setContentView(R.layout.activity_parking_lot_info);
		initActionBar();
		if (getIntent().getSerializableExtra("parkingLot") == null) {
			Toast.makeText(NewParkingLotInfoActivity.this, "车位对象不存在", Toast.LENGTH_LONG).show();
			return;
		} else {
			currentParkingLot = (ParkingLot) getIntent().getSerializableExtra("parkingLot");
			getParkingLotInfo();
			isCurrentLotActivited = currentParkingLot.isHasActivited();
		}
		Log.i("demo", "getSensorCode1=" + currentParkingLot.getSensorCode1());

		// 如果打开本地蓝牙设备不成功，提示信息，结束程序
		if (_bluetooth == null) {
			Toast.makeText(this, "无法打开手机蓝牙，请确认手机是否有蓝牙功能！", Toast.LENGTH_LONG).show();
			finish();
			return;
		}

		// 设置设备可以被搜索
		new Thread() {
			@SuppressLint("NewApi")
			public void run() {
				if (_bluetooth.isEnabled() == false) {
					_bluetooth.enable();
				}
			}
		}.start();
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		if (mConnectedThread != null)
			mConnectedThread.cancel();
	}

	private void initActionBar() {
		((RelativeLayout) findViewById(R.id.button_rpsend)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (isSocket) {
					if (ParkingLotNewEditFragment.getNfcCode().equals("")) {
						Toast.makeText(NewParkingLotInfoActivity.this, "请将信息补充完整", Toast.LENGTH_SHORT).show();
						return;
					}
					sendMessage(HardwareInterfaceTools.getSubmitForConBaseStationMessage(
							ParkingLotNewEditFragment.getNfcCode(), currentParkingLot.getBasestationCode()));
				}

				else {
					Toast.makeText(NewParkingLotInfoActivity.this, "请先连接蓝牙在绑定", Toast.LENGTH_SHORT).show();
				}

			}
		});
		btn = (TextView) findViewById(R.id.textView_tips_bluetooth_status);
		actionbar_progressBar = (ProgressBar) findViewById(R.id.actionbar_progressBar);
		actionbar_textView_title = (TextView) findViewById(R.id.actionbar_textView_title);
		actionbar_refresh_button = (TextView) findViewById(R.id.actionbar_refresh_button);
		jiedian_heart = (Button) findViewById(R.id.jiedian_heart);
		jizhan_heart = (Button) findViewById(R.id.jizhan_heart);
		jiedian_heart.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d("LTP", "“查看节点心跳”被点击");
				DialogFragmentForSensorHeartBeats fragment = new DialogFragmentForSensorHeartBeats();
				Bundle args = new Bundle();
				args.putString("sensorCode", currentParkingLot.getNfcCode());
				args.putBoolean("isCurrentLotActivited", isCurrentLotActivited);
				fragment.setArguments(args);
				fragment.setStyle(DialogFragment.STYLE_NO_TITLE,
						android.R.style.Theme_Holo_Dialog_NoActionBar_MinWidth);
				fragment.show(getFragmentManager(), "SensorHeartBeatsListDialogFragment");
			}
		});

		jizhan_heart.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.d("LTP", "“查看基站心跳”被点击");
				// Bundle args = new Bundle();
				// args.putInt("actionFlag", 1);
				// fragment = new DynamicPickBasestationDialogFragment();
				// fragment.setArguments(args);
				// fragment.setStyle(DialogFragment.STYLE_NO_TITLE,
				// android.R.style.Theme_Holo_Dialog_NoActionBar_MinWidth);
				// fragment.show(fragmentmanager,
				// "DynamicPickBasestationDialogFragment");
				// 请求基站心跳信息
				DialogFragmentForBaseStationHeartBeats fragment = new DialogFragmentForBaseStationHeartBeats();
				Bundle args = new Bundle();
				args.putString("baseStationCode", ParkingLotNewEditFragment.getBasestationText());
				fragment.setArguments(args);
				fragment.setStyle(DialogFragment.STYLE_NO_TITLE,
						android.R.style.Theme_Holo_Dialog_NoActionBar_MinWidth);
				fragment.show(fragmentmanager, "BaseStationHeartBeatsListDialogFragment");
			}
		});
		/** 默认为查看 */
		changeActionbar(currentActionFlag);
		actionbar_refresh_button.setVisibility(View.GONE);
		((ImageView) findViewById(R.id.actionbar_imageView_back_button)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (currentActionFlag == 0) {
					// 查看界面下直接返回即可
					onBackPressed();
				} else if (currentActionFlag == 1) {
					// 交换页面为查看
					currentActionFlag = 0;
					// changeFragment(currentActionFlag);
					NewParkingLotInfoActivity.this.finish();

				}
			}
		});

		actionbar_refresh_button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 刷新数据，或其他操作
				if (currentActionFlag == 0) {
					// 交换页面为编辑
					currentActionFlag = 1;
					changeFragment(currentActionFlag);
				}
			}
		});
		stopProgress();
	}

	/** 改变actionBar之前要先将currentActionFlag进行改变才可以 */
	private void changeActionbar(int currentActionFlag) {
		switch (currentActionFlag) {
		case 0:
			actionbar_textView_title.setText("查看车位");
			actionbar_refresh_button.setVisibility(View.VISIBLE);
			actionbar_refresh_button.setText("编辑");
			break;
		case 1:
			actionbar_textView_title.setText("部署");
			actionbar_refresh_button.setVisibility(View.GONE);
			// actionbar_refresh_button.setText("提交");
			break;
		default:
			break;
		}
	}

	/** 改变Fragment之前要先将currentActionFlag进行改变才可以 */
	private void changeFragment(int currentActionFlag) {
		FragmentTransaction transaction = fragmentmanager.beginTransaction();
		// 先隐藏全部内容
		hideDrawerFragments(transaction);
		// 判断当前抽屉应该要显示的状态值，然后更改抽屉
		if (currentActionFlag == 0) {
			TurnFragmentToCheck(transaction);
		} else if (currentActionFlag == 1) {
			TurnFragmentToEdit(transaction);

		}
		if (transaction == null)
			return;

		transaction.commit();
		changeActionbar(currentActionFlag);
	}

	private void hideDrawerFragments(FragmentTransaction transaction) {
		if (plCheckFragment != null) {
			transaction.hide(plCheckFragment);
		}
		if (plEditFragment != null) {
			transaction.hide(plEditFragment);
		}
	}

	private void TurnFragmentToEdit(FragmentTransaction transaction) {
		if (plEditFragment == null) {
			// plEditFragment = new ParkingLotEditFragment();
			plEditFragment = new ParkingLotNewEditFragment();
			Bundle bundle = new Bundle();
			bundle.putSerializable("parkingLot", currentParkingLot);
			plEditFragment.setArguments(bundle);
			transaction.add(R.id.frameLayout_for_parkingLot, plEditFragment);
		}
		transaction.show(plEditFragment);
	}

	private void TurnFragmentToCheck(FragmentTransaction transaction) {
		if (plCheckFragment == null) {
			plCheckFragment = new ParkingLotCheckFragment();
			Bundle bundle = new Bundle();
			bundle.putSerializable("parkingLot", currentParkingLot);
			plCheckFragment.setArguments(bundle);
			transaction.add(R.id.frameLayout_for_parkingLot, plCheckFragment);
		}
		transaction.show(plCheckFragment);
	}

	private void getParkingLotInfo() {
		// startProgress();
		changeFragment(1);
		// AppContext.getInstance().getVolleyTools()
		// .fetchParkingLotInfo(handler, currentParkingLot.getCode());

	}

	/**
	 * 获取车位上的基站
	 */
	private void getBaseStationInfo() {
		if (currentParkingLot.isHasActivited()) {
			startProgress();
			AppContext.getInstance().getVolleyTools().fetchBasestationInfo(handler,
					currentParkingLot.getBasestationNfcCode());
		}
	}

	private DynamicPickBasestationDialogFragment fragment;
	private DBManager daManager;

	private void openBaseStationPickFragment(int actionCode) {
		Bundle args = new Bundle();
		args.putInt("actionFlag", actionCode);
		switch (actionCode) {
		case 1:
			args.putSerializable("baseStations", daManager.getOriLocSupportBasestations(0, 5));

			break;

		default:
			break;
		}
		if (fragment != null && fragment.isVisible())
			return;
		fragment = new DynamicPickBasestationDialogFragment();
		fragment.setArguments(args);
		fragment.setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo_Dialog_NoActionBar_MinWidth);
		fragment.show(fragmentmanager, "DynamicPickBasestationDialogFragment");
	}

	@Override
	public void onSensorBeClicked(String sensorCode) {
		DialogFragmentForSensorHeartBeats fragment = new DialogFragmentForSensorHeartBeats();
		Bundle args = new Bundle();
		args.putString("sensorCode", sensorCode);
		args.putBoolean("isCurrentLotActivited", isCurrentLotActivited);
		fragment.setArguments(args);
		fragment.setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo_Dialog_NoActionBar_MinWidth);
		fragment.show(getFragmentManager(), "SensorHeartBeatsListDialogFragment");

	}

	@Override
	public void onSensorCodeBeClicked(int index) {
		switch (index) {
		case 0:
			if (("").equals(currentParkingLot.getSensorCode())) {
				if (currentSupportBaseStation == null) {
					Toast.makeText(NewParkingLotInfoActivity.this, "请先添加部署基站", Toast.LENGTH_LONG).show();
					openBaseStationPickFragment(1);
				} else {

				}
				return;
			} else {
				handler.sendMessage(
						handler.obtainMessage(HandlerMessageCodes.HTTP_BUILDER_DELETE_NODE_INFO_SUCCEED, 0, 1));
			}
			break;
		case 1:
			if (("").equals(currentParkingLot.getSensorCode1())) {
				Toast.makeText(NewParkingLotInfoActivity.this, "请先添加部署基站", Toast.LENGTH_LONG).show();
				openBaseStationPickFragment(1);
				return;
			} else {
				handler.sendMessage(
						handler.obtainMessage(HandlerMessageCodes.HTTP_BUILDER_DELETE_NODE_INFO_SUCCEED, 1, 1));
			}
			break;

		default:
			break;
		}
	}

	String newNfcCode;
	String type;

	@Override
	public void onParkingLotEdited(ParkingLot parkinglot) {
		startProgress();
		newNfcCode = parkinglot.getNfcCode();
		if (isSocket) {
			if (parkinglot.getNfcCode().equals("")) {
				Toast.makeText(NewParkingLotInfoActivity.this, "请将信息补充完整", Toast.LENGTH_SHORT).show();
				return;
			}
			if (parkinglot.getCode().length() > 7) {
				type = "1";
			} else {
				type = "2";
			}
			if ("1".equals(type)) {
				// 动态 发送数据
				sendMessage(HardwareInterfaceTools.getDynamicSubmitForConBaseStationMessage(
						currentParkingLot.getNfcCode(), currentParkingLot.getBasestationCode(), ""));

				AppContext.getInstance().getVolleyTools().submitBoundNodes(handler, parkinglot, type);
			} else {
				// 静态 发送数据
				sendMessage(HardwareInterfaceTools.getSubmitForConBaseStationMessage(currentParkingLot.getNfcCode(),
						currentParkingLot.getBasestationCode()));
				Log.i("demo", "currentParkingLot=" + currentParkingLot.getBasestationCode());

				AppContext.getInstance().getVolleyTools().submitBinding(handler, parkinglot, type);
			}

		} else {
			Toast.makeText(NewParkingLotInfoActivity.this, "请先连接蓝牙在绑定", Toast.LENGTH_SHORT).show();
		}

	}

	@Override
	public void onParkingLotDeleted(ParkingLot parkinglot) {
		startProgress();
		// 提交
		AppContext.getInstance().getVolleyTools().deleteLot(handler, parkinglot);
	}

	private String nfcCode = "";

	@Override
	protected void readedCardNeededData(String NFC_CODE) {
		nfcCode = NFC_CODE;
		changeFragment(1);
		currentParkingLot.setNfcCode(nfcCode);
		plEditFragment.refreshParkingLot(currentParkingLot);
		// if (currentSupportBaseStation == null) {
		// Toast.makeText(NewParkingLotInfoActivity.this, "请先添加部署基站",
		// Toast.LENGTH_LONG).show();
		// openBaseStationPickFragment(1);
		// } else {
		// handler.sendEmptyMessage(HandlerMessageCodes.HTTP_BUILDER_SUBMIT_BASESTATION_MAPPING_SUCCEED);
		// }
	}

	private TextView btn;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_CONNECT_DEVICE: // 连接结果，由DeviceListActivity设置返回
			// 响应返回结果
			if (resultCode == Activity.RESULT_OK) { // 连接成功，由DeviceListActivity设置返回
				// MAC地址，由DeviceListActivity设置返回
				Log.i("demo", "DeviceListActivity设置返回+++++");
				String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
				// 得到蓝牙设备句柄
				_device = _bluetooth.getRemoteDevice(address);

				// 用服务号得到socket
				try {
					_socket = _device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));
					mConnectedThread = new ConnectedThread(_socket);
				} catch (IOException e) {
					Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
					isSocket = false;
				}
				// 连接socket
				try {
					_socket.connect();
					Toast.makeText(this, "连接" + _device.getName() + "成功！", Toast.LENGTH_SHORT).show();
					btn.setText("断开");
					isSocket = true;
				} catch (IOException e) {
					try {
						Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
						_socket.close();
						_socket = null;
						isSocket = false;
					} catch (IOException ee) {
						Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
						isSocket = false;
					}

					return;
				}

				// 打开接收线程
				try {
					is = _socket.getInputStream(); // 得到蓝牙数据输入流
				} catch (IOException e) {
					Toast.makeText(this, "接收数据失败！", Toast.LENGTH_SHORT).show();
					return;
				}
				if (bThread == false) {
					ConnectedThread r;
					mConnectedThread.start();
					bThread = true;
				} else {
					bRun = true;
				}
			}
			break;
		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 使用非同步的方式写数据
	 * 
	 * @param message
	 *            要写出的数据
	 */
	public void sendMessage(String message) {
		// 创建一个临时对象
		ConnectedThread r;
		// 同步同一个ConnectedThread对象
		synchronized (this) {
			r = mConnectedThread;
		}
		// 执行写不同步
		r.write(message);
	}

	private class ConnectedThread extends Thread {
		private final BluetoothSocket mmSocket;
		private final InputStream mmInStream;
		private final OutputStream mmOutStream;

		public ConnectedThread(BluetoothSocket socket) {
			mmSocket = socket;
			InputStream tmpIn = null;
			OutputStream tmpOut = null;
			// 获得蓝牙通信需要的输入输出流
			try {
				tmpIn = socket.getInputStream();
				tmpOut = socket.getOutputStream();
			} catch (IOException e) {

			}
			mmInStream = tmpIn;
			mmOutStream = tmpOut;
		}

		public void run() {
			byte[] buffer = new byte[1024];
			byte[] bu_temp = new byte[1024];
			int bytes;
			int bytes_temp = 0;
			// 在连接了之后保持对输入的监听
			// 这里使用死循环一直等待并接收数据
			try {
				while ((bytes = mmInStream.read(buffer, 0, 1024)) > -1) {

					// 得到输入的数据
					// bytes = mmInStream.read(buffer);
					Log.v("demo", "数据尺寸：" + bytes);
					// 将接收到的数据返回给 UI Activity
					bytes_temp += bytes;
					for (int i = bytes_temp - bytes; i < bytes_temp; i++) {
						bu_temp[i] = buffer[i - (bytes_temp - bytes)];
					}
					// if (bytes_temp == 12) {
					// if (CHexConver.byte2HexStr(bu_temp,
					// bytes_temp).startsWith("AA220000"))
					// mHandler.obtainMessage(HandlerCode.BLUETOOTH_MESSAGE_READED_STREAM,
					// CHexConver.byte2HexStr(bu_temp,
					// bytes_temp)).sendToTarget();
					// bytes_temp = 0;
					// }
					String s = CHexConver.byte2HexStr(bu_temp, bytes_temp).replace(" ", "");
					Log.v("demo", "数据累计:" + s);
					if (s.length() > 12 && (s.split("AA220000", 2).length > 1)) {
						s = s.split("AA220000", 2)[1];
						if (s.length() >= 16) {
							s = s.substring(0, 16);
							Log.v("demo", "数据解析:" + s);
							handler1.obtainMessage(1000, "AA220000" + s).sendToTarget();
							bytes_temp = 0;
						}
					}
				}
			} catch (IOException e) {
				// connectionLost();
				// // 出问题后从连接监听重新开始
				// BluetoothChatService.this.start();
				e.printStackTrace();
			}

		}

		/**
		 * 朝连接上的设备发送数据
		 * 
		 * @param message
		 *            要发送的数据
		 */
		public void write(String message) {
			try {
				byte[] buffer = CharacterTool2.HexString2Bytes(message);
				mmOutStream.write(buffer);
				// 将已经发送完成的数据返回给 UI Activity
				handler1.obtainMessage(1001, CHexConver.byte2HexStr(buffer, buffer.length)).sendToTarget();
			} catch (IOException e) {

			}
		}

		public void cancel() {
			try {
				mmInStream.close();
				mmOutStream.close();
				mmSocket.close();
			} catch (IOException e) {

			}
		}
	}

	// 蓝牙消息处理队列
	Handler handler1 = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Log.i("demo", "smsg=" + smsg); // 显示数据
			// sv.scrollTo(0, dis.getMeasuredHeight()); // 跳至数据最后一页
			switch (msg.what) {
			case 1000:
				Toast.makeText(NewParkingLotInfoActivity.this, "READED:" + msg.obj, Toast.LENGTH_SHORT).show();
				NewParkingLotInfoActivity.this.handlerBluetoothMessageReaded((String) msg.obj);
				break;
			case 1001:
				Toast.makeText(NewParkingLotInfoActivity.this, "WRITED:" + msg.obj, Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		}
	};

	// 连接按键响应函数
	@SuppressLint("NewApi")
	public void onConnectButtonClicked(View v) {
		if (_bluetooth.isEnabled() == false) { // 如果蓝牙服务不可用则提示
			Toast.makeText(this, " 打开蓝牙中...", Toast.LENGTH_LONG).show();
			// 我们通过startActivityForResult()方法发起的Intent将会在onActivityResult()回调方法中获取用户的选择，比如用户单击了Yes开启，
			// 那么将会收到RESULT_OK的结果，
			// 如果RESULT_CANCELED则代表用户不愿意开启蓝牙
			// Intent mIntent = new
			// Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			// startActivityForResult(mIntent, 1);
			// 用enable()方法来开启，无需询问用户(实惠无声息的开启蓝牙设备),这时就需要用到android.permission.BLUETOOTH_ADMIN权限。
			BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
			mBluetoothAdapter.enable();
			// mBluetoothAdapter.disable();//关闭蓝牙
			return;
		}

		// 如未连接设备则打开DeviceListActivity进行设备搜索
		TextView btn = (TextView) findViewById(R.id.textView_tips_bluetooth_status);
		if (_socket == null) {
			Intent serverIntent = new Intent(this, DeviceListActivity.class);
			// // 跳转程序设置
			startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE); //
		} else {
			// 关闭连接socket
			try {

				is.close();
				_socket.close();
				_socket = null;
				bRun = false;
				btn.setText("连接");
			} catch (IOException e) {
			}
		}
		return;
	}

	private void handlerBluetoothMessageReaded(String message) {
		// TODO 处理部署基站发送的指令
		Log.i("demo", "message=" + HardwareInterfaceTools.HandlerResponseMessage(message));
		switch (HardwareInterfaceTools.HandlerResponseMessage(message)) {
		case 0:
			// ParkingSpa p = new ParkingSpa();
			// p.setNfc(HardwareInterfaceTools.HandlerResponseMessageContext(message));
			// Toast.makeText(MainActivity.this,"节点正在保存！",Toast.LENGTH_SHORT).show();
			// fragment_sen.upParkingSensorStatus(p,
			// AppContext.getInstance().getSpTools().readIntPreferences(SharedPreferencesTools.BINDING_INDEX_TABLE,
			// p.getNfc()));
			break;
		case 1:
			ParkingLot p = new ParkingLot();
			p.setSensorCode(HardwareInterfaceTools.HandlerResponseMessageContext(message));
			Toast.makeText(NewParkingLotInfoActivity.this, p.getSensorCode(), Toast.LENGTH_SHORT).show();
			Toast.makeText(NewParkingLotInfoActivity.this, "节点：" + p.getNfcCode() + " 设置成功！", Toast.LENGTH_SHORT)
					.show();
			sendMessage(message);
			bindingFinished(p, 0);
			break;
		default:
			break;
		}
	}

	/**
	 * 蓝牙返回绑定成功的信息后会执行该方法通知UI更新
	 */
	private void bindingFinished(ParkingLot parkingSpa, int index) {
		// fragment_sen.upParkingSensorStatusFinished(parkingSpa, index);
		setResult(15);
		onBackPressed();
	}

	private void startProgress() {
		actionbar_progressBar.setIndeterminate(false);
		actionbar_progressBar.setVisibility(View.VISIBLE);
		actionbar_refresh_button.setVisibility(View.GONE);
	}

	private void stopProgress() {
		actionbar_progressBar.setIndeterminate(true);
		actionbar_progressBar.setVisibility(View.GONE);
		actionbar_refresh_button.setVisibility(View.VISIBLE);
	}

}
